package com.tfswue.lh.controller;

import com.tfswue.lh.entity.User;
import com.tfswue.lh.service.impl.UserServiceImpl;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户控制器
 */
@RestController
public class UserController {

    @Autowired
    private UserServiceImpl userService;

    /**
     * 获取所有用户
     * @return 用户列表
     */
    @GetMapping("/user")
    public Map<String, Object> getUser() {
        Map<String, Object> response = new HashMap<>();
        try {
            List<User> users = userService.list();
            response.put("success", true);
            response.put("data", users);
            response.put("count", users.size());
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取用户列表失败: " + e.getMessage());
        }
        return response;
    }

    /**
     * 根据ID获取用户
     * @param id 用户ID
     * @return 用户信息
     */
    @GetMapping("/user/{id}")
    public Map<String, Object> getUserById(@PathVariable Integer id) {
        Map<String, Object> response = new HashMap<>();
        try {
            User user = userService.getById(id);
            response.put("success", true);
            response.put("data", user);
            if (user == null) {
                response.put("message", "用户不存在");
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取用户失败: " + e.getMessage());
        }
        return response;
    }

    /**
     * 获取用户总数
     * @return 用户总数
     */
    @GetMapping("/user/count")
    public Map<String, Object> getUserCount() {
        Map<String, Object> response = new HashMap<>();
        try {
            long count = userService.count();
            response.put("success", true);
            response.put("count", count);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取用户总数失败: " + e.getMessage());
        }
        return response;
    }

    /**
     * 会话管理
     * @param session HTTP会话
     * @return 会话信息
     */
    @RequestMapping("/session")
    public String session(HttpSession session) {
        session.setAttribute("username", "lh");
        System.out.println(session.getAttribute("username"));
        return "session end";
    }
}